var demo_h5_upload_ops = {
    init:function(){
        this.eventBind();
        this.img=''
    },
    eventBind:function(){
        var that = this;
        $("#upload").change(function(){
            var reader = new FileReader();
            reader.onload = function (e) {
                that.compress(this.result);
            };
            reader.readAsDataURL(this.files[0]);
        });
        $("#up-load").click(function(){
            that.upload()
        })
    },
    compress : function (res) {
        var that = this;
        var img = new Image(),
            maxH = 300;

        img.onload = function () {
            var cvs = document.createElement('canvas'),
                ctx = cvs.getContext('2d');

            if(img.height > maxH) {
                img.width *= maxH / img.height;
                img.height = maxH;
            }
            cvs.width = img.width;
            cvs.height = img.height;

            ctx.clearRect(0, 0, cvs.width, cvs.height);
            ctx.drawImage(img, 0, 0, img.width, img.height);
            var dataUrl = cvs.toDataURL('image/jpeg', 1);
            
            $(".img_wrap").attr("src",dataUrl);
            that.img=dataUrl
            $(".img_wrap").show();
            // 上传略
            //that.upload( dataUrl );
        };

        img.src = res;
    },
    upload:function( image_data ){
        var name = $('#name').val()
        var attr = $('#attr').val()
        var p = $('#position').val()
        var price=$('#price').val()
        if (name==''){
            alert("物品名称 不能为空")
            return false;
        }
        if(attr==''){
            alert('物品属性不能为空')
            return false;
        }
        if(p==''){
            alert('物品位置 不能为空')
            return false;
        }
        if(price==''){
           alert('加载评估不能为空')
           return false;
        }else{
            var re = /^[0-9]+.?[0-9]+$/; //判断字符串是否为数字 //判断正整数 /^[1-9]+[0-9]*]*$/
            if (!re.test(price))
            {
                alert("请输入数字(例:0.02)");
                return false;
            }
        }

        if(this.img==''){
            alert('请拍摄图片')
            return false;
        }
        var itemdata={
            name:name,
            attr:attr,
            pos:p,
            price:price,
            image_data:this.img,
        }
        console.log(itemdata)
        $.ajax({
            url:"/upitem",
            type:'POST',
            data:JSON.stringify(itemdata),
            dataType:'text',
            success:function( res ){
                var reso=JSON.parse(res)
                alert(reso['desc'])
            }
        });
    },
};


$(document).ready( function(){
    demo_h5_upload_ops.init();
} );

